package com.zzptc.sky.translate.Fragment;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.anye.greendao.gen.EntriesDao;
import com.google.gson.Gson;
import com.zzptc.sky.translate.HttpUtil;
import com.zzptc.sky.translate.MyApplication;
import com.zzptc.sky.translate.R;
import com.zzptc.sky.translate.ben.Entries;
import com.zzptc.sky.translate.ben.FanYi;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

public class TranslateFragment extends Fragment {
    EditText e;
    ListView listView;
    Adapter adapter;
    private String urlString;
    private EntriesDao entriesDao;
    ImageButton imageButton;
    TextView sourceTv,translationTv;
    String tag;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=View.inflate(getActivity(),R.layout.activity_translate,null);

        sourceTv = (TextView) view.findViewById(R.id.sourceTv); //中文按钮
        translationTv = (TextView) view.findViewById(R.id.translationTv); //英文按钮
        listView = (ListView) view.findViewById(R.id.listView);//输出结果框
        imageButton = (ImageButton) view.findViewById(R.id.exchange_btn);//语言切换按钮
        e = (EditText) view.findViewById(R.id.edtext);//编辑框
        //适配器
        adapter = new Adapter();
        listView.setAdapter(adapter);
        //数据库
        entriesDao = MyApplication.getInstances().getDaoSession().getEntriesDao();

        Log.e("--", "@@@@@@@@@");
        //TODO  网络请求
        view.findViewById(R.id.btn_fanyi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    urlString = "http://dict.youdao.com/suggest?q="+URLEncoder.encode(e.getText().toString(),"UTF-8")
                            +"&le=zh&num=5&ver=2.0&doctype=json&keyfrom=mdict.7.2.0.android&model=honor&mid" +
                            "=5.6.1&imei=659135764921685&vendor=wandoujia&screen=1080x1800&ssid=superman&abtest=2";
                    HttpUtil.get(urlString,h);
                } catch (UnsupportedEncodingException e1) {
                    e1.printStackTrace();
                }
            }
        });
        //TODO 翻译语种的相互转换
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tag = sourceTv.getText().toString().trim();
                sourceTv.setText(translationTv.getText().toString().trim());
                translationTv.setText(tag);
            }
        });
        return view;
    }

    List<FanYi.Entries> list = new ArrayList<FanYi.Entries>();
    Handler h = new Handler(){
        @Override public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                Gson gson = new Gson();
                FanYi fanYi =  gson.fromJson(msg.obj.toString(),FanYi.class);
                List<FanYi.Entries> entriesList = fanYi.getData().getEntries();
                //TODO   通过GreenDao查询是否已经存在    如果不存在则insert 数据库并刷新复习本记录
                List<Entries> entriesList1 = entriesDao.queryBuilder().where(EntriesDao.Properties.Entry.eq(entriesList.get(0).getEntry())).list();
                if (entriesList1.size() <= 0 || entriesList1 == null) {
                    Entries entries = new Entries();
                    entries.setEntry(entriesList.get(0).getEntry());
                    entries.setExplain(entriesList.get(0).getExplain());
                    entriesDao.insert(entries);
                    //TODO   通过调用TheWordFragment的静态方法notifyDataSetChanged() 来刷新复习本
                    TheWordFragment.notifyDataSetChanged();
                }
                //TODO   先清空list  再向list 添加 查询到的数据  并刷新界面
                list.clear();
                for (int i = 0;i<entriesList.size();i++){
                    FanYi.Entries entr = entriesList.get(i);
                    list.add(entr);
                }
                adapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
//适配器
    class Adapter extends BaseAdapter{

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
/*
 * int position位置 判断显示在界面上的是第几个，通过position在BaseAdapter自定义的数组或者集合中取值。并展示在界面上
 * View converView 展示在界面上的一个item  滑出屏幕的converView就在下面新进来的item中重新使用，只是修改下他展示的值
 * ViewGroup parent 这个属性是加载xml视图时使用。
  */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            FanYi.Entries d = list.get(position);
//TODO 当convertView为空时 就显示出list_item页面
            if (convertView == null){
                convertView = getActivity().getLayoutInflater().inflate(R.layout.list_item,null);
            }
           //只是修改下他展示的值
            TextView tete1 = (TextView) convertView.findViewById(R.id.tete1),
                    tete2 = (TextView) convertView.findViewById(R.id.tete2);
            tete1.setText(""+d.getEntry());
            tete2.setText(""+d.getExplain());
            return convertView;
        }
    }
}
